package com.cloud.apis.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.cloud.apis.core.exception.CustomException;
import com.cloud.apis.core.model.Dict;
import com.cloud.apis.core.model.PageData;
import com.cloud.apis.core.model.Role;
import com.cloud.apis.core.model.User;
import com.cloud.apis.core.utils.PageInfoToPageDataConverterUtil;
import com.cloud.apis.core.web.ServiceCode;
import com.cloud.apis.mail.service.MailService;
import com.cloud.apis.message.model.MessageEntity;
import com.cloud.apis.message.task.MessageTask;
import com.cloud.apis.message.utils.MessageSendUtil;
import com.cloud.apis.organization.db.dao.AdminMapper;
import com.cloud.apis.organization.db.dao.OrganizationMapper;
import com.cloud.apis.organization.db.dao.PostMapper;
import com.cloud.apis.user.db.dao.PermissionMapper;
import com.cloud.apis.user.db.dao.RoleMapper;
import com.cloud.apis.user.db.dao.UserMapper;
import com.cloud.apis.user.pojo.form.*;
import com.cloud.apis.user.pojo.vo.DimissiomInfoVo;
import com.cloud.apis.user.pojo.vo.UserInfoVo;
import com.cloud.apis.user.service.IUserService;
import com.cloud.apis.websocket.WebSocketServe;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户相关API接口业务层实现
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2024/3/20
 */
@Slf4j
@Service
public class UserService implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private MessageTask messageTask;
    @Autowired
    private MailService mailService;
    @Autowired
    private WebSocketServe webSocketServe;
    @Value("${custom-config.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Value("${custom-config.secret}")
    private String secret;
    @Value("${custom-config.password}")
    private String password;

    public UserService() {
        log.info("【UserService】");
    }

    @Override
    public HashMap login(HashMap param) {
        //设置密钥未为账号和系统密钥进行加密
        param.put("secret",param.get("account")+secret);
        //实现登录
        HashMap map = userMapper.login(param);
        //判断用户名和密码错误的情况
        if(map==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"用户名或密码错误");
        }
        // 从返回的map中获取用户id
        Long userId = MapUtil.getLong(map, "id");
        //判断用户是否存在
        if (userId==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }else {
            //判断用户是否离职
            if(userMapper.selectUserById(userId)==null){
                throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"用户已离职无法登录系统");
            }
        }
        return map;
    }

    @Override
    public User selectUserByAccount(String account) {
        return userMapper.selectUserByAccount(account);
    }

    @Override
    public void register(User user, Long[] roleIds) {
        //判断角色是否存在
        for(Long roleId : roleIds){
            if(roleMapper.selectRoleById(roleId)==null){
                throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"角色不存在");
            }
        }
        //判断组织是否存在
        if(organizationMapper.selectOrganizationById(user.getOrganizationId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"组织不存在");
        }
        //判断岗位是否存在
        if(postMapper.selectPostById(user.getJobId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"岗位不存在");
        }
        //插入用户
        int num = userMapper.insertUser(user,user.getAccount()+secret);
        //注册失败
        if(num<=0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"注册失败");
        }
        //获取用户id
        Long id = user.getId();
        //判断用户其关联的角色是否存在
        for (Long roleId : roleIds){
            if(userMapper.isExistRole(id,roleId)){
                //删除用户
                int exNum = userMapper.deleteUserById(id);
                if(exNum<=0){
                    throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"出现了异常请及时联系系统管理员");
                }
                throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"用户已经有该角色，请重新注册");
            }
        }
        //关联用户和角色
        int exNum = userMapper.insertUserRole(id,roleIds);
        if(exNum<=0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"出现了异常请及时联系系统管理员");
        }
        //发送相关邮件
        mailService.sendEntryMail(id,new String[]{user.getEMail()});
    }

    @Override
    public ArrayList<String> searchUserPermission(Long userId) {
        if(userMapper.selectUserById(userId)==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        //根据用户id查询角色id
        ArrayList<Long> roleList = userMapper.searchUserRole(userId);
        if (roleList != null && roleList.size() > 0) {
            //根据角色id查询权限id
            ArrayList<Long> permissions = roleMapper.searchRolePermission(roleList);
            if(permissions.size()==0){
                return null;
            }
            //根据权限id查询权限代码
            return permissionMapper.searchUserPermission(permissions);
        }else {
            return null;
        }
    }

    @Override
    public HashMap getUserInfo(Long id) {
        HashMap map = new HashMap();
        UserInfoVo userInfoVo = userMapper.selectUserById(id);
        if(userInfoVo==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        //根据用户id查询角色id
        ArrayList<Long> roleList = userMapper.searchUserRole(id);
        if (roleList != null && roleList.size() > 0) {
            //根据角色id查询角色信息
            ArrayList<Role> roles = roleMapper.selectRoleInfosByRoleIds(roleList);
            map.put("roles",roles);
        }else {
            map.put("roles","无");
        }
        map.put("user",userInfoVo);
        return map;
    }

    @Override
    public Boolean validPassword(Long id, String password) {
        if(userMapper.selectUserById(id)==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        //根据用户id查询账号
        String account = userMapper.selectAccountByUserId(id);
        if (account==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"账号不存在");
        }
        return userMapper.isUserIdAndPassWord(id,password,account+secret);
    }

    @Override
    public Boolean updatePassword(Long id, String password) {
        if(userMapper.selectUserById(id)==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        //根据用户id查询账号
        String account = userMapper.selectAccountByUserId(id);
        if (account==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"账号不存在");
        }
        if(userMapper.updateUserPassword(id,password,account+secret)){
            MessageSendUtil.sendSimpleMessage(messageTask,id,"系统消息","您的密码已经成功修改，请记住密码如果忘记请联系相关工作人员进行重置");
            webSocketServe.sendMessage(id);
            return true;
        }else {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"修改密码失败");
        }
    }

    @Override
    public String updateDescription(Long id, String description) {
        UserInfoVo userInfoVo = userMapper.selectUserById(id);
        if(userInfoVo==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        Boolean result = userMapper.updateUserDescription(id,description);
        if (result){
            return userMapper.selectUserById(id).getDescription();
        }else {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"修改失败");
        }
    }

    @Override
    public String updateMotto(Long id, String motto) {
        UserInfoVo userInfoVo = userMapper.selectUserById(id);
        if(userInfoVo==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        Boolean result = userMapper.updateUserMotto(id,motto);
        if (result){
            webSocketServe.sendMessage(id);
            MessageSendUtil.sendSimpleMessage(messageTask,id,"系统消息","您的座右铭成功修改");
            return userMapper.selectUserById(id).getMotto();
        }else {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"修改失败");
        }
    }

    @Override
    public String getAccount(Long id) {
        if(userMapper.selectUserById(id)==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        return userMapper.selectAccountByUserId(id);
    }

    @Override
    public String updateAccount(Long id, String account) {
        UserInfoVo user = userMapper.selectUserById(id);
        if(user==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        if (userMapper.selectUserByAccount(account)!=null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"账号已存在");
        }
        Boolean result = userMapper.updateUserAccount(id,user.getAccount()+secret,account,user.getPassword(),account+secret);
        if (result){
            MessageSendUtil.sendSimpleMessage(messageTask,id,"系统消息","您的账号已经成功修改");
            webSocketServe.sendMessage(id);
            return userMapper.selectUserById(id).getAccount();
        }else {
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"修改失败");
        }
    }

    @Override
    public Integer updateAvater(Long id, String url) {
        if(userMapper.selectUserById(id)==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        MessageSendUtil.sendSimpleMessage(messageTask,id,"系统消息","您的头像已经成功登记或修改");
        webSocketServe.sendMessage(id);
        return userMapper.updateUserAvater(id,url);
    }

    @Override
    public String getEmail(Long id) {
        if(userMapper.selectUserById(id)==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        return userMapper.selectEmailByUserId(id);
    }

    @Override
    public PageData<UserInfoVo> listUser(Integer pageNum,Long userId) {
        return listPage(pageNum, defaultQueryPageSize,userId);
    }

    @Override
    public PageData<UserInfoVo> listPage(Integer pageNum, Integer pageSize,Long userId) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfoVo> list = userMapper.list(userId);
        PageInfo<UserInfoVo> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public void updateUserInfo(Long id, UpdateUserInfoForm form) {
        if (userMapper.selectUserById(id)==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        int num = userMapper.updateUserInfo(id,form);
        if (num<=0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"修改失败");
        }
    }

    @Override
    public Boolean resetPassword(Long id) {
        if (userMapper.selectUserById(id)==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        return updatePassword(id,password);
    }

    @Override
    public PageData<UserInfoVo> listSearchResult(SearchUserForm form) {
       return searchByName(form.getPageNum(),defaultQueryPageSize,form);
    }

    @Override
    public PageData<UserInfoVo> searchByName(Integer pageNum, Integer pageSize, SearchUserForm form) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfoVo> list = userMapper.searchByName(form);
        PageInfo<UserInfoVo> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public void updateRegistration(UpdateRegistrationForm form) {
        if (userMapper.selectUserById(form.getId())==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        int num = userMapper.updateRegistration(form.getId(),form.isStatus());
        if (num<=0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"修改失败");
        }
    }

    @Override
    public PageData<UserInfoVo> listgroupOrgUserList(GroupOrgUserListForm form) {
        return listgroupOrgUserListPage(form.getPageNum(),defaultQueryPageSize,form);
    }

    @Override
    public PageData<UserInfoVo> listgroupOrgUserListPage(Integer pageNum, Integer pageSize, GroupOrgUserListForm form) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfoVo> list = userMapper.listgroupOrgUserListPage(form.getOrgIds(), form.getUserId());
        PageInfo<UserInfoVo> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public PageData<UserInfoVo> searchInOrganizationids(GroupOrgUserSearchForm form) {
        return searchInOrganizationidsPage(form.getPageNum(),defaultQueryPageSize,form);
    }

    @Override
    public PageData<UserInfoVo> searchInOrganizationidsPage(Integer pageNum, Integer pageSize, GroupOrgUserSearchForm form) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfoVo> list = userMapper.searchInOrganizationidsPage(form.getOrgIds(),form.getSearchName(),form.getUserId());
        PageInfo<UserInfoVo> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public PageData<UserInfoVo> getAllUserList(GetAllUserListForm form) {
        return getAllUserListPage(form.getPageNum(),defaultQueryPageSize,form);
    }

    @Override
    public PageData<UserInfoVo> getAllUserListPage(Integer pageNum, Integer pageSize, GetAllUserListForm form) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfoVo> list = userMapper.getAllUserListPage(form.getId());
        PageInfo<UserInfoVo> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public void updateUserOrgAndPost(UpdateUserOrgAndPostForm form) {
        if (userMapper.selectUserById(form.getId())==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        if(organizationMapper.selectOrganizationById(form.getOrganizationId())==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"组织不存在");
        }
        if(postMapper.selectPostById(form.getPostId())==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"岗位不存在");
        }
        if(!adminMapper.selectAdminByUserId(form.getId()).isEmpty()){
            adminMapper.deleteAssignsByAdminId(form.getId());
        }
        int num = userMapper.updateUserOrgAndPost(form);
        if (num<=0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"修改失败");
        }
    }

    @Override
    public DimissiomInfoVo setDimission(DimissiomForm form) {
        UserInfoVo userInfoVo = userMapper.selectUserById(form.getUserId());
        if(userInfoVo==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        int num = userMapper.setDimission(form);
        if (num<=0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"修改失败");
        }
        return userMapper.selectDimissionInfoById(form.getId());
    }

    @Override
    public void updateUserDimission(Long id) {
        UserInfoVo userInfoVo = userMapper.selectUserById(id);
        if(userInfoVo==null){
            throw new CustomException(ServiceCode.ERROR_NOT_FOUND.getValue(),"用户不存在");
        }
        //发送相关邮件
        mailService.sendOutMail(id,new String[]{userInfoVo.getEMail()});
        int num = userMapper.updateUserDimission(id);
        if (num<=0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"修改失败");
        }
        StpUtil.logout(id);

    }

    @Override
    public JSONObject searchUserContactList() {
        Long id = StpUtil.getLoginIdAsLong();
        UserInfoVo userInfoVo = userMapper.selectUserById(id);
        //与当前用户所在组织的用户id
        ArrayList<Long> userIds =  userMapper.selectUserByOrganizationId(userInfoVo.getOrganizationId());
        //管理当前用户所在组织的用户id
        ArrayList<Long> adminIds =  adminMapper.selectAdminByOrganizationId(userInfoVo.getOrganizationId());
        //去除两者中的重复id
        Set<Long> set = new HashSet<>();
        set.addAll(userIds);
        set.addAll(adminIds);
        System.out.println(set);
        //将SET转换为ArrayList
        userIds = new ArrayList<>(set);
        ArrayList<HashMap> list = userMapper.searchUserContactList(userIds);
        String letter = null;
        JSONObject json = new JSONObject(true);
        JSONArray array = null;
        for (HashMap<String, String> map : list) {
            String name = map.get("name");
            String firstLetter = PinyinUtil.getPinyin(name);
            firstLetter = firstLetter.toUpperCase();
            if (letter == null || !letter.equals(firstLetter)) {
                letter = firstLetter;
                array = new JSONArray();
                json.set(letter, array);
            }
            array.put(map);
        }
        return json;
    }

    @Override
    public PageData<UserInfoVo> getAllOutUserList(GetAllUserListForm form) {
        return getAllOutUserListPage(form.getPageNum(),defaultQueryPageSize,form);
    }

    @Override
    public PageData<UserInfoVo> getAllOutUserListPage(Integer pageNum, Integer pageSize, GetAllUserListForm form) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfoVo> list = userMapper.getAllOutUserListPage(form.getId());
        PageInfo<UserInfoVo> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public Integer getAllPeopleCount() {
        return userMapper.getAllPeopleCount();
    }

    @Override
    public PageData<UserInfoVo> listgroupOrgOutUserList(GroupOrgUserListForm form) {
        return listgroupOrgOutUserListPage(form.getPageNum(),defaultQueryPageSize,form);
    }

    @Override
    public PageData<UserInfoVo> listgroupOrgOutUserListPage(Integer pageNum, Integer pageSize, GroupOrgUserListForm form) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfoVo> list = userMapper.listgroupOrgOutUserListPage(form.getOrgIds(), form.getUserId());
        PageInfo<UserInfoVo> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }


}
